package cn.dnf.controller;

import cn.dnf.domain.Relation;
import cn.dnf.domain.Ticket;
import cn.dnf.domain.User;
import cn.dnf.feign.MovieFeignClients;
import cn.dnf.service.IUserService;
import cn.dnf.util.JsonResult;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@Autowired
private MovieFeignClients movieFeignClients;

    @GetMapping("/buy/{id}")
    public JsonResult buy(@PathVariable Long id){
        try {
            Ticket ticket = movieFeignClients.findById(id);
            ticket.setStock(ticket.getStock()-1);
            movieFeignClients.update(ticket);
            User user = userService.findById(1L);
            user.setBalance(user.getBalance()-ticket.getPrice());
            userService.update(user);
            return JsonResult.me().setMessage("购买成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult().setMessage("购买失败");
        }
    }

    @GetMapping("/findAllMovies")
    public List<Ticket> findAllMovies(){
        return movieFeignClients.findAll();
    }

    @GetMapping("/watch/{id}")
    public JsonResult watch(@PathVariable Long id){

            return movieFeignClients.watch(id);

    }

    @RequestMapping("/register")
    public JsonResult register(@RequestBody User user){
        try {
            userService.add(user);
            movieFeignClients.gift(user);
            return JsonResult.success().setMessage("注册成功，免费获得一张电影票");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();

        }
    }


}
